<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 01.12.13
 * Time: 17:54
 */
class Tourism_AdminToursController extends Core_Controller_Action_Admin
{
  public function indexAction()
  {
    $this->view->formFilter = $formFilter = new Tourism_Form_Admin_Filter();
    /** @var $citiesTable Tourism_Model_DbTable_Tours */
    $citiesTable = Engine_Api::_()->getDbTable('tours', 'tourism');
    $this->view->paginator = $p = $citiesTable->getToursPaginator($this->_getAllParams());
    $formFilter->populate(array('title' => $this->_getParam('title', '')));
  }

  public function createAction()
  {
    $this->view->form = $form = new Tourism_Form_Tours_Create();

    if ($this->getRequest()->isPost()) {
      if ($form->isValid($this->getRequest()->getPost())) {
        $toursTable = Engine_Api::_()->getDbTable('tours', 'tourism');
        /**
         * @var $citiesTable Tourism_Model_DbTable_Cities
         */
        $tour = $toursTable->createRow();
        $tour->setFromArray($form->getValues());
        $tour->setPhoto($form->photo);
        $tour->save();
        return $this->_helper->redirector->gotoRoute(array('module' => 'tourism', 'controller' => 'tours', 'action' => 'index'), 'admin_default', true);
      }
    }
  }

  public function editAction()
  {
    /** @var $toursTable Tourism_Model_DbTable_Tours */
    $tour_id = $this->_getParam('id');
    $this->view->form = $form = new Tourism_Form_Tours_Create();
    $toursTable = Engine_Api::_()->getDbTable('tours', 'tourism');
    $tour = $toursTable->getTour($tour_id);
    if ($this->getRequest()->isPost()) {
      if ($form->isValid($this->getRequest()->getPost())) {
        $values = $form->getValues();
        if (!$values['photo']) {
          unset($values['photo']);
        }
        $tour->setFromArray($values);
        $tour->save();

        return $this->_helper->redirector->gotoRoute(array('module' => 'tourism', 'controller' => 'tours', 'action' => 'index'), 'admin_default', true);
      }
    }
    $form->populate($tour->toArray());
  }


  public function deleteAction()
  {
    $tour_id = $this->_getParam('id');
    $this->view->form = $form = new Tourism_Form_Tours_Delete();
    $toursTable = Engine_Api::_()->getDbTable('tours', 'tourism');
    $this->view->tour = $tour = $toursTable->getTour($tour_id);
    if ($this->getRequest()->isPost()) {
      if ($form->isValid($this->getRequest()->getPost())) {
        $tour->delete();
        return $this->_helper->redirector->gotoRoute(array('module' => 'tourism', 'controller' => 'tours', 'action' => 'index'), 'admin_default', true);
      }
    }
  }
}